<?php


/**
 * Notes:
 * PROJECT_NAME : ERP v1.8 重构erp
 * User: 夏鱼儿<397072174@qq.com>
 * Date: 2024/6/4
 * Time: 17:00
 */

namespace app\command\company;

use app\company\model\DeliverLine;
use app\company\model\StoreOrder;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use app\company\model\DeliverTask as DeliverTaskModel;

class DeliverTask extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('deliver:task')->setDescription('司机任务创建(创建运单)')
             ->addArgument('date', Option::VALUE_REQUIRED, '日期', '');
    }


    protected function execute(Input $input, Output $output)
    {
        $output->writeln('司机任务创建(创建运单)开始');
        $date = $input->getArgument('date');
        if (!$date) $date = date('Ymd');
        $date  = date('Y-m-d', strtotime($date));
        $start = date("Y-m-d", strtotime("-1 day", strtotime($date))) . config('platform.deliver_task.start_time');
        $end   = $date . config('platform.deliver_task.end_time');
        $model = new DeliverLine();
        $model->startTrans();
        try {
            $model->where('status', 1)->select()->each(function ($item) use ($date, $start, $end, $output) {
                //根据路线生成运单
                $task                    = new DeliverTaskModel();
                $task->company_id        = $item->company_id;
                $task->deliver_line_id   = $item->id;
                $task->deliver_line_no   = $item->no;
                $task->deliver_driver_id = $item->deliver_driver_id;
                $task->warehouse_id      = $item->warehouse_id;
                $task->save();
                //生成运单编号
                $task->no = "YD" . date('Ymd', strtotime($date)) . getPaddedNumber($task->id, 8);
                $task->save();
                //关联订单 已发货的订单
                $store_ids = $item->stores()->column('id');
                $num       = StoreOrder::whereIn('store_id', $store_ids)->whereBetweenTime('create_time', $start, $end)->where('order_status', 3)->update([
                    'deliver_task_id' => $task->id
                ]);
                if ($num == 0) $task->delete();//当没有关联订单时，删除运单
            });
            $model->commit();
            $output->writeln($date . '司机任务创建(创建运单)成功');
        } catch (\Exception $e) {
            $model->rollback();
            $output->writeln('司机任务创建(创建运单)失败' . $e->getMessage() . $e->getLine() . $e->getFile());
        }
    }
}